package com.pay.wechat.handler;

import com.pay.mapper.PayMerchantInfoMapper;
import com.pay.wechat.builder.TextBuilder;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {
    
    @Autowired
    private PayMerchantInfoMapper payMerchantInfoMapper;
    
    /**
     * 用户取消关注的时候会走这个回调函数
     * @param wxMessage
     * @param context
     * @param wxMpService
     * @param sessionManager
     * @return
     */
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        this.logger.info("取消关注用户 OPENID: " + openId);
        
        // 更新本地数据库为取消关注状态
        int i = payMerchantInfoMapper.updateContactWxOpenid(openId);
        return i > 0 ? setResult("取消关注成功", wxMessage,wxMpService)
                : setResult("取消关注失败", wxMessage,wxMpService);
    }
    
    private WxMpXmlOutMessage setResult(String content, WxMpXmlMessage wxMessage,
                                        WxMpService service) {
        return new TextBuilder().build(content, wxMessage, service);
    }

}
